<template>
  <div class="toolbar-container">
    <!-- 第一行 - 主要功能按钮 -->
    <div class="toolbar-row">
      <div class="toolbar-button-group">
        <el-button link type="primary" icon="el-icon-folder-opened" @click="handleOpen">
          打开
        </el-button>
        <el-button link type="primary" icon="el-icon-folder-add" @click="handleNew">
          新建工程
        </el-button>
        <el-button link type="primary" icon="el-icon-files" :disabled="!settings || !settings.projectPath"
          @click="handleSave">
          保存
        </el-button>
        <el-button link type="primary" icon="el-icon-view" :disabled="!settings || !settings.projectPath"
          @click="handlePreview">
          仿真
        </el-button>
        <el-button link type="primary" icon="el-icon-view" :disabled="!settings || !settings.projectPath"
          @click="handlePagePreview">
          页面仿真
        </el-button>
        <el-button link type="primary" icon="el-icon-document" title="系统代码" :disabled="!settings || !settings.projectPath"
          @click="handleEditCode">
          系统代码
        </el-button>
        <el-button link type="primary" icon="el-icon-download" :disabled="!settings || !settings.projectPath"
          @click="handleDownload">
          导出U盘
        </el-button>
        </div>
        <div class="toolbar-button-group">
        <el-button link type="primary" icon="el-icon-document-copy" :disabled="!designer || !designer.selectedWidget"
          @click="handleCopy">
          复制
        </el-button>
        <el-button link type="primary" icon="el-icon-document-copy" :disabled="!designer || !designer.selectedWidget"
          @click="handleCopyPage">
          整页复制
        </el-button>
        <el-button link type="primary" icon="el-icon-download" :disabled="!settings || !settings.projectPath"
          @click="handlePaste">
          粘贴
        </el-button>
      </div>
      <div class="toolbar-button-group">
        <el-button link type="primary" icon="el-icon-tools" :disabled="!settings || !settings.projectPath"
          @click="handleSetting">
          系统设置
        </el-button>
        <el-button link type="primary" icon="el-icon-tools" :disabled="!settings || !settings.projectPath"
          @click="languSettingOpen">
          语言设置
        </el-button>
        <el-button link type="primary" icon="el-icon-refresh" :disabled="!settings || !settings.projectPath"
          @click="handleChangeResolution">
          切换分辨率
        </el-button>
        <!-- <el-button link type="primary" :disabled="!settings || !settings.projectPath" @click="handleId">
          ID
        </el-button> -->
        <div class="zoom-group">
          <el-text class="zoom-text">{{ `${zoomValue}%` }}</el-text>
          <el-button link type="primary" icon="el-icon-minus" :disabled="!settings || !settings.projectPath"
            @click="handleMinusZoom"></el-button>
          <el-slider v-model="zoomValue" :min="50" :max="150" :step="1" :disabled="!settings || !settings.projectPath"
            size="small" :show-tooltip="false" @change="handleZoom" />
          <el-button link type="primary" icon="el-icon-plus" :disabled="!settings || !settings.projectPath"
            @click="handlePlusZoom"></el-button>
        </div>
      </div>
    </div>

    <!-- 第二行 - 删除/撤销/清空/重做按钮 -->
    <div class="toolbar-row">
      <div class="toolbar-button-group">
        <el-button link type="primary" icon="el-icon-close-bold" :disabled="!designer || !designer.selectedWidget"
          @click="handleDelete">
          删除
        </el-button>
        <el-button link type="primary" :disabled="!settings || !settings.projectPath" @click="clearFormWidget">
          <svg-icon icon-class="el-delete" />
          {{ i18nt('designer.toolbar.clear') }}
        </el-button>
        <el-button link type="primary" :disabled="undoDisabled" :title="i18nt('designer.toolbar.undoHint')"
          @click="undoHistory">
          <svg-icon icon-class="undo" />
          {{ i18nt('designer.toolbar.undoHint') }}
        </el-button>
        <el-button link type="primary" :disabled="redoDisabled" :title="i18nt('designer.toolbar.redoHint')"
          @click="redoHistory">
          <svg-icon icon-class="redo" />
          {{ i18nt('designer.toolbar.redoHint') }}
        </el-button>
        <el-button link type="primary" :disabled="!settings || !settings.projectPath" @click="handleData">
          <svg-icon icon-class="number-field" />
    地址信息
  </el-button>
      </div>
    </div>

    


  <el-dialog v-model="showResolutionDialog" title="切换分辨率" width="500">
    <el-form>
      <el-form-item label="目标分辨率" required>
        <el-radio-group v-model="targetResolution">
          <el-radio-button 
            v-for="res in availableResolutions" 
            :key="res" 
            :label="res" 
            :value="res" 
          />
        </el-radio-group>
      </el-form-item>
      <el-form-item label="保存路径" required>
        <el-input v-model="savePath" placeholder="请选择保存路径" disabled>
          <template #suffix>
            <el-icon class="el-input__icon" @click="selectSavePath">
              <el-icon-folder-opened />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="showResolutionDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmChangeResolution">确认</el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog v-model="showSettingDialog" size="large" :title="settingDialogTitle" width="500">
    <el-form size="large">
      <el-form-item v-show="isNewProjiect" label="工程目录" :required="true">
        <el-input v-model="settingsForm.projectPath" placeholder="请选择工程目录" disabled>
          <template #suffix>
            <el-icon class="el-input__icon"
              :style="{ fontSize: '20px', marginLeft: 0, color: '#409eff', cursor: 'pointer' }"
              @click="handleOpenUserPath">
              <el-icon-folder-opened />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      
      <!-- 修改屏幕尺寸选择为型号选择 -->
      <el-form-item v-show="isNewProjiect" label="型号选择" :required="true">
        <el-select v-model="settingsForm.model" placeholder="请选择型号" @change="handleModelChange">
          <el-option
            v-for="item in modelOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      
      <!-- 添加产品参数说明 -->
      <el-form-item v-show="isNewProjiect" label="设备参数" :required="true">
    <div class="model-description">
      <template v-if="settingsForm.model === 'LP070-101'">
        <div>屏幕尺寸：7英寸</div>
        <div>分辨率：1024*600</div>
      </template>
      <template v-if="settingsForm.model === 'LP101-101'">
        <div>屏幕尺寸：10英寸</div>
        <div>分辨率：1280*800</div>
      </template>
      <template v-if="settingsForm.model === 'LP101-201'">
        <div>屏幕尺寸：10英寸</div>
        <div>分辨率：1024*600</div>
      </template>
      <template v-if="settingsForm.model === 'EP043-101'">
        <div>屏幕尺寸：4.3英寸</div>
        <div>分辨率：480*272</div>
      </template>
    </div>
  </el-form-item>
      
      <el-form-item v-show="isNewProjiect" label="屏幕方向" :required="true">
        <el-radio-group v-model="settingsForm.screenOrientation">
          <el-radio-button label="0" :value="0" />
          <el-radio-button label="90" :value="1" />
          <el-radio-button label="180" :value="2" />
          <el-radio-button label="270" :value="3" />
        </el-radio-group>
      </el-form-item>
      <el-form-item v-show="!isNewProjiect" label="串口号" :required="true">
        <el-select v-model="settingsForm.serialPort" :loading="loadingPorts" placeholder="检测串口设备中..."
          @focus="loadSerialPorts">
          <el-option v-for="port in serialPortList" :key="port.value" :label="port.label" :value="port.value" />
          <el-option v-if="serialPortList.length === 0" disabled :value="null" label="未检测到串口设备" />
        </el-select>
      </el-form-item>

      <el-form-item v-show="!isNewProjiect" label="波特率" :required="true">
        <el-select v-model="settingsForm.baudRate">
          <el-option v-for="item in baudRateOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handlerSettingCancel">取消</el-button>
        <el-button v-if="isNewProjiect" type="primary" @click="handleNewProject">
          创建工程
        </el-button>
        <el-button v-else type="primary" @click="handlerSettingOK"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog v-model="showLanguDialog" title="设置语言" width="700">
    <el-form label-width="120px" class="demo-dynamic">
      <el-form-item label="语言 1">
        <el-input style="width: 450px" value="font_1.ttf" disabled />
      </el-form-item>
      <el-form-item v-for="(item, index) in languages" :label="'语言 ' + (index +2)" :key="item.text">
        <el-select v-model="item.value" placeholder="选择字体..." style="width: 240px">
          <el-option v-for="item2 in fontList" :key="item2.name" :label="item2.name" :value="item2.name">
            {{ item2.name }}
          </el-option>
          <el-option @click.prevent="removeDomain(item)">
            <span style="color: red">删除此语言</span>
          </el-option>
        </el-select>
        <el-input v-model="item.desc" placeholder="此语言描述" style="width: 200px;margin-left: 10px;" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="addDomain"> 增加语言 </el-button>
        <el-button @click="languSettingCancel">取消</el-button>
        <el-button type="primary" @click="languSettingOk"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog v-model="isExporting" title="导出项目" width="30%" :close-on-click-modal="false" :close-on-press-escape="false"
    :show-close="false" style="border-radius: 12px; background: #f5f5f5;">
    <div style="text-align: center; padding: 10px 20px;">
      <p
        style="font-size: 25px; margin-bottom: 15px; color: #409EFF; font-weight: 600;">
        正在导出，请稍候...</p>
    </div>
  </el-dialog>

  <el-dialog v-model="showExportSuccess" title="导出完成" width="30%" style="border-radius: 12px; background: #f5f5f5;">
    <div style="text-align: center; padding: 30px 20px;">
      <p
        style="font-size: 25px; margin-bottom: 15px; color: #409EFF; font-weight: 600; letter-spacing: 1px;">
        导出成功！</p>
    </div>
    <template #footer>
      <span class="dialog-footer"
        style="display: block; background: #f5f5f5; padding: 0px; text-align: center; border-radius: 0 0 12px 12px;">
        <el-button type="primary" @click="showExportSuccess = false"
          style="padding: 18px 30px; border-radius: 8px; font-weight: 550;">
          确 定
        </el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog v-model="showExportDialog" title="导出选项" width="500">
  <el-form>
    <el-form-item label="导出DATA数据">
      <el-switch v-model="exportDataFiles" />
    </el-form-item>
  </el-form>
  <template #footer>
    <div class="dialog-footer">
      <el-button @click="showExportDialog = false">取消</el-button>
      <el-button type="primary" @click="confirmExport">确认导出</el-button>
    </div>
  </template>
</el-dialog>
</div>
</template>

<script>
import * as ELECTRON from '@/electron'
import * as EVENTS from '../event'

const settingsInit = {
  projectPath: '',
  widthAndHeight: '1024*600',
  scale: 100,
  screenOrientation: 0,
  baudRate: 115200
}

const baudRateOptions = [
  { label: '300', value: 300 },
  { label: '600', value: 600 },
  { label: '1200', value: 1200 },
  { label: '2400', value: 2400 },
  { label: '4800', value: 4800 },
  { label: '9600', value: 9600 },
  { label: '14400', value: 14400 },
  { label: '19200', value: 19200 },
  { label: '38400', value: 38400 },
  { label: '56000', value: 56000 },
  { label: '57600', value: 57600 },
  { label: '115200', value: 115200 },
  { label: '128000', value: 128000 },
  { label: '256000', value: 256000 }
]

export default {
  name: 'ToolbarPanel',
  inject: ['getDesignerConfig'],
  props: {
    designer: Object,
    settings: Object
  },
  data() {
    return {
      showExportDialog: false,
      exportDataFiles: false,
      showResolutionDialog: false,
      targetResolution: '',
      savePath: '',
      isExporting: false,
      showExportSuccess: false,
      designerConfig: this.getDesignerConfig(),
      portCheckInterval: null,
      zoomValue: this.settings && this.settings.scale ? this.settings.scale : 100,
      isNewProjiect: false,
      showSettingDialog: false,
      settingsForm: { ...settingsInit },
      languages: [],
      fontList: [],
      showLanguDialog: false,
      baudRateOptions,
      serialPortList: [],
      loadingPorts: false,
      modelOptions: [
      { value: 'LP070-101', label: 'LP070-101' },
      { value: 'LP101-101', label: 'LP101-101' },
      { value: 'LP101-201', label: 'LP101-201' },
      { value: 'EP043-101', label: 'EP043-101' }
    ],
    }
  },
  computed: {
    availableResolutions() {
      if (!this.settings || !this.settings.width || !this.settings.height) {
        return ['1280*800', '1024*600', '800*480']
      }
      
      const currentRes = `${this.settings.width}*${this.settings.height}`
      return ['1280*800', '1024*600', '800*480'].filter(res => res !== currentRes)
    },
    settingDialogTitle() {
      return this.isNewProjiect ? '新建工程' : '设置'
    },
    undoDisabled() {
      if (!this.designer) {
        return true
      }
      return !this.designer.undoEnabled()
    },
    redoDisabled() {
      if (!this.designer) {
        return true
      }
      return !this.designer.redoEnabled()
    }
  },
  watch: {
    settings(value) {
      if (value) {
        const { width, height, scale, ...rest } = value
        this.zoomValue = scale
        this.settingsForm = {
          widthAndHeight: `${width}*${height}`,
          scale,
          ...rest
        }
        if (this.serialPortList.length === 0 && !this.loadingPorts) {
          this.loadSerialPorts()
        }
      } else {
        this.settingsForm = { ...settingsInit }
      }
    }
  },
  mounted() {
    this.loadSerialPorts()
    this.setupPortMonitoring()
    
    this.$emitter.on(ELECTRON.OPEN_USER_PATH_RESULT, (projectPath) => {
      this.settingsForm.projectPath = projectPath
    })

    this.$emitter.on(EVENTS.GET_FONT_RESOURCE_LIST_RESULT, (fontList) => {
      this.languages = []
      this.fontList = []
      fontList.forEach((key) => {
        this.fontList.push({ name: key })
      })

      let languages = this.settings.languages
      if (languages) {
        this.languages = languages
      }
    })
  },
  beforeUnmount() {
    this.cleanupPortMonitoring()
  },
  unmounted() {
    this.$emitter.off(ELECTRON.OPEN_USER_PATH_RESULT)
  },
  methods: {
    handleData() {
  if (this.designer) {
    this.designer.setShowWidgetData(!this.designer.showWidgetData)
  }
},
    handleModelChange(model) {
  // 根据选择的型号设置对应的分辨率
  let resolution = '1024*600'; // 默认值
  
  switch(model) {
    case 'LP070-101':
      resolution = '1024*600';
      break;
    case 'LP101-101':
      resolution = '1280*800';
      break;
    case 'LP101-201':
      resolution = '1024*600';
      break;
    case 'EP043-101':
      resolution = '480*272';
      break;
    default:
      // 如果没有匹配的型号，使用第一个选项的分辨率
      resolution = this.modelOptions[0].value === 'LP101-101' ? '1280*800' : '1024*600';
      break;
  }
  
  this.settingsForm.widthAndHeight = resolution;
},
    handleChangeResolution() {
      if (!this.settings || !this.settings.projectPath) {
        this.$message.warning('请先打开一个项目')
        return
      }
      
      // 默认选择第一个可用分辨率
      this.targetResolution = this.availableResolutions[0]
      this.savePath = ''
      this.showResolutionDialog = true
    },
    
    async selectSavePath() {
      try {
        const result = await window.electronAPI.showOpenDialog({
          properties: ['openDirectory', 'createDirectory'],
          title: '选择保存目录'
        })
        
        if (!result.canceled && result.filePaths.length > 0) {
          this.savePath = result.filePaths[0]
        }
      } catch (error) {
        console.error('选择目录失败:', error)
        this.$message.error('选择目录失败: ' + error.message)
      }
    },
    
    async confirmChangeResolution() {
      if (!this.savePath) {
        this.$message.error('请选择保存路径')
        return
      }
      
      try {
        this.$message.info('正在切换分辨率，请稍候...')
        
        // 获取当前项目配置
        const currentConfig = await this.getCurrentProjectConfig()
        
        if (!currentConfig) {
          throw new Error('获取当前项目配置失败')
        }
        
        // 计算缩放比例
        const [currentWidth, currentHeight] = [this.settings.width, this.settings.height]
        const [targetWidth, targetHeight] = this.targetResolution.split('*').map(Number)
        
        const scaleX = targetWidth / currentWidth
        const scaleY = targetHeight / currentHeight
        
        // 克隆并调整配置
        const newConfig = JSON.parse(JSON.stringify(currentConfig))
        
        // 更新设置
        newConfig.settings.width = targetWidth
        newConfig.settings.height = targetHeight
        
        // 调整所有页面和组件
        newConfig.pages.forEach(page => {
          // 调整页面背景
          if (page.options.bgType === 1) { // 纯色背景
            // 不需要调整
          } else if (page.options.bgType === 2) { // 图片背景
            // 可能需要调整图片位置，这里暂时不处理
          }
          
          // 调整所有组件
          this.scaleWidgets(page.widgetList, scaleX, scaleY)
        })
        
        // 保存为新项目
        const result = await this.saveAsProject(newConfig, this.savePath)
        
        if (result && result.success) {
          this.$message.success('分辨率切换成功！')
          this.showResolutionDialog = false
        } else {
          throw new Error(result?.error || '保存项目失败')
        }
        
      } catch (error) {
        console.error('切换分辨率失败:', error)
        this.$message.error('切换分辨率失败: ' + error.message)
      }
    },
    
    async getCurrentProjectConfig() {
      try {
        return await window.electronAPI.getCurrentProjectConfig()
      } catch (error) {
        console.error('获取项目配置失败:', error)
        return null
      }
    },
    
    async saveAsProject(config, path) {
      try {
        return await window.electronAPI.saveAsProject({ config, path })
      } catch (error) {
        console.error('保存项目失败:', error)
        return { success: false, error: error.message }
      }
    },
    
    scaleWidgets(widgetList, scaleX, scaleY) {
      widgetList.forEach(widget => {
        // 调整位置和尺寸
        if (widget.options.x !== undefined) {
          widget.options.x = Math.round(widget.options.x * scaleX)
        }
        if (widget.options.y !== undefined) {
          widget.options.y = Math.round(widget.options.y * scaleY)
        }
        if (widget.options.width !== undefined) {
          widget.options.width = Math.round(widget.options.width * scaleX)
        }
        if (widget.options.height !== undefined) {
          widget.options.height = Math.round(widget.options.height * scaleY)
        }
        
        // 调整字体大小（可选）
        if (widget.options.fontSize !== undefined) {
          // 按宽度比例缩放字体，或取较小比例
          const fontScale = Math.min(scaleX, scaleY)
          widget.options.fontSize = Math.round(widget.options.fontSize * fontScale)
        }
        
        // 递归处理子组件
        if (widget.widgetList && widget.widgetList.length > 0) {
          this.scaleWidgets(widget.widgetList, scaleX, scaleY)
        }
      })
    },
    setupPortMonitoring() {
      if (window.electronAPI?.onSerialPortsUpdate) {
        window.electronAPI.onSerialPortsUpdate((ports) => {
          this.updatePortList(ports)
        })
      } else {
        this.portCheckInterval = setInterval(() => {
          this.loadSerialPorts()
        }, 2000)
      }
    },
    cleanupPortMonitoring() {
      if (window.electronAPI?.onSerialPortsUpdate) {
        window.electronAPI.onSerialPortsUpdate(null)
      }
      if (this.portCheckInterval) {
        clearInterval(this.portCheckInterval)
      }
    },
    updatePortList(ports) {
      if (ports.length > 0) {
        this.serialPortList = ports.map(p => ({
          value: p.path.match(/^COM(\d+)/i)[1],
          label: `${p.path}${p.manufacturer ? ` (${p.manufacturer})` : ''}`
        }))
        
        if (!this.serialPortList.some(p => p.value === this.settingsForm.serialPort)) {
          this.settingsForm.serialPort = null
        }
        
        if (!this.settingsForm.serialPort && this.serialPortList.length > 0) {
          this.settingsForm.serialPort = this.serialPortList[0].value
        }
      } else {
        this.serialPortList = [{
          value: '1',
          label: '未检测到串口设备(默认COM1)',
          disabled: true
        }]
        this.settingsForm.serialPort = '1'
      }
    },
    async loadSerialPorts() {
      try {
        const ports = await window.electronAPI.getSerialPorts()
        this.updatePortList(ports)
      } catch (error) {
        console.error('刷新串口列表失败:', error)
      }
    },
    handleOpen() {
      this.$emitter.emit(ELECTRON.OPEN_PROJECT)
    },
    handleNew() {
      this.newProject()
    },
    newProject() {
      this.isNewProjiect = true
      this.settingsForm.model = this.modelOptions[0].value
      this.handleModelChange(this.modelOptions[0].value)
      this.showSettingDialog = true
    },
    handleNewProject() {
      this.showSettingDialog = false
      const settings = this.getSettings()
      this.$emitter.emit(ELECTRON.INIT_WORKSPACE_SETTINGS, JSON.parse(JSON.stringify(settings)))
    },
    getSettings() {
    const { projectPath, model, widthAndHeight, ...rest } = this.settingsForm;
    const size = widthAndHeight.split('*').map((str) => parseInt(str));

    return {
      ...rest,
      width: size[0],
      height: size[1],
      ...(this.isNewProjiect ? { projectPath } : {})
    }
  },
    handleOpenUserPath() {
      this.$emitter.emit(ELECTRON.OPEN_USER_PATH)
    },
    handleSave() {
  this.$emitter.emit(EVENTS.SAVE_ALL_CODE_TABS, {
    callback: () => {
      // 保存完成后不需要额外操作，因为已经在 saveAllUnsavedCodeTabs 中触发了保存
    }
  });
  this.$message.success('保存成功');
},
    handleCompile() {
      this.$emitter.emit(ELECTRON.EXPORT_LUA_SCRIPT)
    },
    handlePreview() {
    this.$emitter.emit(EVENTS.SAVE_ALL_CODE_TABS, {
      callback: () => {
        this.$emitter.emit(ELECTRON.CLEAR_DEBUG_LOG);
        this.$emitter.emit(ELECTRON.START_DEBUG);
      }
    });
  },
    handlePagePreview() {
    this.$emitter.emit(EVENTS.SAVE_ALL_CODE_TABS, {
      callback: () => {
        this.$emitter.emit(ELECTRON.CLEAR_DEBUG_LOG);
        this.$emitter.emit(
          ELECTRON.START_PAGE_DEBUG,
          (this.designer && this.designer.options.name) || ''
        );
      }
    });
  },
    handleEditCode() {
      this.$emitter.emit(EVENTS.OPEN_CODE_EDITOR)
    },
    async handleDownload() {
  if (!this.settings || !this.settings.projectPath) return;

  // 保存所有未保存的代码
  await new Promise((resolve) => {
    this.$emitter.emit(EVENTS.SAVE_ALL_CODE_TABS, {
      callback: () => {
        resolve();
      }
    });
  });

  // 显示导出选项对话框
  this.showExportDialog = true;
},
async confirmExport() {
  this.showExportDialog = false;
  
  try {
    const { canceled, filePaths } = await window.electronAPI.showOpenDialog({
      properties: ['openDirectory'],
    });
    if (canceled) return;
    const exportPath = filePaths[0];

    this.isExporting = true;
    await window.electronAPI.exportProject({
      exportPath,
      exportDataFiles: this.exportDataFiles
    });
    this.isExporting = false;
    this.showExportSuccess = true;
  } catch (error) {
    console.error('导出失败:', error);
    this.isExporting = false;
    this.$message.error('导出失败，请重试');
  }
},
    handleCopy() {
      if (this.designer && this.designer.selectedWidget) {
        this.designer.copySelectedWidget(this.designer.selectedWidget)
      }
    },
    handleCopyPage() {
      if (this.designer) {
        this.$confirm(`确定要复制 ${this.designer.options.name} 整个页面吗？`)
          .then(() => {
            this.$emitter.emit(EVENTS.COPY_PAGE, this.designer)
          })
          .catch(() => {})
      }
    },
    handlePaste() {
      if (this.designer) {
        this.designer.pasteWidget()
      }
    },
    deleteWidget(widget) {
      this.designer.deleteWidget(widget, this.designer.widgetList)
      return
    },
    handleDelete() {
      if (this.designer && this.designer.selectedWidget) {
        this.$confirm(`确定要删除 ${this.designer.selectedWidget.options.name} 组件吗？`)
          .then(() => {
            this.deleteWidget(this.designer.selectedWidget)
          })
          .catch(() => {})
      }
    },
    clearFormWidget() {
      this.$confirm('确定要清空页面的组件吗？')
        .then(() => {
          this.designer.clearDesigner()
          this.designer.formWidget.clearWidgetRefList()
        })
        .catch(() => {})
    },
    handleSetting() {
      this.$emitter.emit(EVENTS.OPEN_SETTING)
    },
    languSettingOpen() {
      this.$emitter.emit(EVENTS.GET_FONT_RESOURCE_LIST)
      this.$nextTick(() => {
        this.showLanguDialog = true
        console.log('langu', this.fontList)
      })
    },
    languSettingCancel() {
      this.showLanguDialog = false
    },
    languSettingOk() {
      this.settings.languages = this.languages
      this.handleSave();
      this.showLanguDialog = false
    },
    addDomain() {
      this.languages.push({
        value: '',
        desc: ''
      })
    },
    removeDomain(item) {
      var index = this.languages.indexOf(item)
      if (index !== -1) {
        this.languages.splice(index, 1)
      }
    },
    openSettingModal(isNewProjiect) {
      this.isNewProjiect = isNewProjiect
      this.showSettingDialog = true
      if (!isNewProjiect) {
        this.loadSerialPorts()
      }
    },
    handlerSettingCancel() {
      this.showSettingDialog = false
    },
    handlerSettingOK() {
      this.showSettingDialog = false
      const settings = this.getSettings()
      this.$emitter.emit(EVENTS.SAVE_SETTING, settings)
    },
    handleId() {
      if (this.designer) {
        this.designer.setShowWidgetId(!this.designer.showWidgetId)
      }
    },
    handleZoom(value) {
      this.settings.scale = this.zoomValue = value
      this.$nextTick(() => {
        this.handleSave()
      })
    },
    handlePlusZoom() {
      this.zoomValue += 1
      if (this.zoomValue > 150) {
        this.zoomValue = 150
      }
      this.settings.scale = this.zoomValue
      this.$nextTick(() => {
        this.handleSave()
      })
    },
    handleMinusZoom() {
      this.zoomValue -= 1
      if (this.zoomValue < 50) {
        this.zoomValue = 50
      }
      this.settings.scale = this.zoomValue
      this.$nextTick(() => {
        this.handleSave()
      })
    },
    showToolButton(configName) {
      if (this.designerConfig[configName] === undefined) {
        return true
      }
      return !!this.designerConfig[configName]
    },
    undoHistory() {
      this.designer.undoHistoryStep()
    },
    redoHistory() {
      this.designer.redoHistoryStep()
    }
  }
}
</script>

<style lang="scss" scoped>
/* 添加旋转动画 */
@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 工具栏按钮背景色*/
$--toolbar-button-background: #e0eeff;
$--toolbar-button-hover-background: #ffeaa6;

/* 工具栏按钮鼠标滑过背景色*/

.toolbar-container {
  margin-top: 4px;
  font-size: 16px;

  :after {
    display: block;
    content: '';
    clear: both;
  }

  :deep(.el-button) {
    margin-left: 5px;
    color: $--app-font-color;

    &.is-disabled {
      color: $--app-disabled-font-color;
    }

    &:hover {
      background-color: $--toolbar-button-hover-background;
    }

    span {
      font-size: 14px;
    }
  }

  .toolbar-button-group {
    display: flex;
    float: left;
    height: 25px;
    line-height: 25px;
    margin-left: 5px;
    border-radius: 4px;
    border-bottom: #6f9dd9 1px solid;
    background-color: $--toolbar-button-background;

    .zoom-group {
      display: inline-flex;
      position: relative;
      width: 160px;

      .zoom-text {
        position: absolute;
        line-height: 24px;
        width: 40px;
        text-align: right;
      }

      .zoom-text + button {
        margin-left: 38px;
      }

      :deep(.el-slider__button-wrapper) {
        width: 24px;
        height: 24px;
        top: -7px;

        .el-slider__button {
          width: 12px;
          height: 12px;
        }
      }
    }
  }

  .el-button i {
    margin-right: 3px;
  }
}
:deep(.el-dialog) {
  .dialog-footer {
    /* 确认按钮（蓝色背景，白色文字） */
    .el-button--primary {
      color: white !important;
      background-color: #409EFF !important;
      
      &:hover {
        background-color: #66b1ff !important;
      }
    }
    
    /* 取消按钮（白色背景，黑色文字） */
    .el-button:not(.el-button--primary) {
      color: #808080 !important;
      background-color: #fff !important;
      border: 1px solid #dcdfe6 !important;
      
      &:hover {
        color: #000 !important;
        background-color: #f5f7fa !important;
        //border-color: #c0c4cc !important;
      }
    }
  }
}

.el-dialog__header {
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  padding: 15px 20px;
}

.el-dialog__title {
  font-size: 18px;
  font-weight: bold;
}
.model-description {
  padding: 8px 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  //border-left: 4px solid #409EFF;
  font-size: 14px;
  color: #606266;
  line-height: 1.5;
  
  div {
    margin: 0;
    white-space: nowrap; /* 防止文字换行 */
  }
  
  div:first-child {
    margin-bottom: 4px; /* 第一行和第二行之间的间距 */
  }
}
</style>